package com.tsj.spzx.feignInterceptor;

import com.alibaba.excel.util.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class UserTokenFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 1. 安全获取请求上下文
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (!(requestAttributes instanceof ServletRequestAttributes)) {
            return; // 非Web请求上下文直接跳过
        }

        // 2. 安全获取请求对象
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        // 3. 获取并验证token
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)) {
            requestTemplate.header("token", token);
        }
    }
}
